package com.qunar.support.service;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.junit.Test;

import com.qunar.support.dao.LoginLogDao;
import com.qunar.support.dao.UserDao;
import com.qunar.support.util.SingleUserManager;

public class UserService {
	static Logger logger = Logger.getLogger(UserService.class);
	/**
	 * 登陆逻辑
	 * @param username
	 * @param password
	 * @param ip
	 * @return
	 */
	public int login(String username,String password,String ip){
		UserDao ud=new UserDao();
		LoginLogDao lld=new LoginLogDao();
		int status=status(username);
		if(status==-1){
			return -1;//逻辑删除，返回用户密码错误
		}else if(status==2){
			return 0;//禁止登陆
		}
		int  uid=ud.validate(username, password);
		lld.logLogin(uid, ip);
		HttpSession thatSession=SingleUserManager.getSession(uid);
		logger.info(getClass()+":"+thatSession);
		if(thatSession!=null){
			logger.info(getClass()+":"+uid+"被踢下线");
			thatSession.invalidate();
		}
		return uid;
	}
	/**
	 * 返回所有用户
	 * @return
	 */
	public JSONArray getAllUser(){
		UserDao ud=new UserDao();
		return ud.getAllUser();
	}
	/**
	 * 返回某个用户的过期天数
	 * @param uid
	 * @return
	 */
	public int overdueDay(int uid){
		UserDao ud=new UserDao();
		int day=ud.overdueDay(uid);
		return day;
	}
	/**
	 * 返回某个用户的状态
	 * @param username
	 * @return
	 */
	public int status(String username){
		UserDao ud=new UserDao();
		int status=ud.active(username);
		return status;
	}
	
	/**
	 * 操作一个用户，包括启禁删(1,2,-1)，还有重置密码(3)
	 * @param uid
	 * @param opt
	 * @return 
	 * 0x1.2b3dddfb42752p-2
	 * 0x1.618fa649bb0bcp-3
	 * 0x1.902515a425d7p-5
	 */
	public String opetateUser(int uid,int opt){
		UserDao ud=new UserDao();
		if(opt==3){
			Double d=Math.random();
			String target=Double.toHexString(d).substring(4,12);
			logger.info(getClass()+": 生成随机密码:"+target);
			ud.resetPassword(uid, target);
			return target;//密码
		}
		ud.operateUser(uid, opt);
		return "OK";
	}
	
	/**
	 * 检查用户名是否存在，0代表没有
	 * @param username
	 * @return
	 */
	public int checkUsername(String username){
		return 0;
	}
	@Test
	public void run(){
		Double d=Math.random();
		logger.info(d);
		logger.info(Double.toHexString(d));
	}
}
